package com.eco.fanliapp.utils;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

public class WebUtil {
	private static Logger log = LogManager.getLogger(WebUtil.class);
	//okhttp mediatype
	public static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
	private static ThreadLocal<OkHttpClient> okHttpClientThreadLocal = ThreadLocal.withInitial(OkHttpClient::new);


	/**
	 * okhttpclient 同步 提交POST数据
	 * @param url 链接
	 * @param json  JSON数据
	 * @return String 请求结果
	 * @throws IOException
	 */
	public static String post(String url, String json) throws IOException {
		RequestBody body = RequestBody.create(mediaType, json);
		Request request = new Request.Builder()
				.url(url)
				.post(body)
				.build();
		okhttp3.Response response = okHttpClientThreadLocal.get().newCall(request).execute();
		if (response.isSuccessful()) {
			return response.body().string();
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}

	/**
	 * okhttpclient 同步 发送get请求
	 * @param url 网址
	 * @throws Exception
	 */
	public static String get(String url) throws Exception {
		Request request = new Request.Builder()
				.url(url)
				.build();

		okhttp3.Response response = okHttpClientThreadLocal.get().newCall(request).execute();
		if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

		return response.body().string();
	}
}
